<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            style="min-width: 230px"
            v-model="listQuery.name"
            placeholder="输入内容"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
        <!-- <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
            >批量删除</el-button
          >
        </el-form-item> -->
      </el-form>
      <el-table
        :data="datas"
        border
        v-loading="listLoading"
        fit
        highlight-current-row
        style="width: 100%"
        size="small"
        @selection-change="handleSelectionChange"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          align="left"
          :width="column.width ? column.width : ''"
          :formatter="dataFormatter"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getAccountList"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="600px">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="收款账号" prop="name">
              <el-input
                type="string"
                v-model="form.name"
                placeholder="收款账号"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="默认账号" prop="default">
              <el-select
                v-model="form.default"
                placeholder="默认账号"
                size="small"
                clearable
              >
                <el-option
                  v-for="item in defaults"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="账号类型" prop="account_type">
          <el-select
            v-model="form.account_type"
            placeholder="账号类型"
            size="small"
            clearable
          >
            <el-option
              v-for="item in types"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="银行名称" prop="bank">
          <el-input
            type="string"
            v-model="form.bank"
            placeholder="银行名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="银行账号" prop="account">
          <el-input
            type="string"
            v-model="form.account"
            placeholder="银行账号"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="初始资金" prop="init_money">
          <el-input
            v-model="form.init_money"
            placeholder="初始资金"
            clearable
            size="small"
            @input="form.init_money = form.init_money.replace(/[^\d|.]/g, '')"
          >
            <el-button slot="append">元</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input
            v-model="form.balance"
            placeholder="余额"
            clearable
            size="small"
            @input="form.balance = form.balance.replace(/[^\d|.|-]/g, '')"
          >
            <el-button slot="append">元</el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="handleSave(false)"
          >保存</el-button
        >
        <el-button type="primary" size="small" @click="handleSave(true)"
          >保存并新增</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import {
  getAccounts,
  addAccount,
  updateAccount,
  delAccount,
} from "@/api/finance";

const defaultForm = {
  id: null,
  name: "",
  default: null,
  account_type: null,
  bank: "",
  account: "",
  init_money: 0,
  balance: 0,
};

export default {
  name: "Account",
  components: {
    Pagination,
  },
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        name: [
          {
            type: "string",
            required: true,
            message: "请输入收付款账号",
            trigger: "blur",
          },
        ],
      },
      types: [
        {
          id: 0,
          name: "银行账号",
        },
        {
          id: 1,
          name: "现金账号",
        },
        {
          id: 2,
          name: "其他",
        },
      ],

      defaults: [
        {
          id: 0,
          name: "否",
        },
        {
          id: 1,
          name: "是",
        },
      ],

      tableColumns: [
        {
          key: "name",
          title: "收付款账号",
        },
        {
          key: "init_money",
          title: "初始金额",
        },
        {
          key: "balance",
          title: "余额",
        },
        {
          key: "bank",
          title: "银行名称",
        },
        {
          key: "account",
          title: "银行账号",
        },
        {
          key: "default_name",
          title: "默认账号",
        },
        {
          key: "account_type_name",
          title: "账号类型",
        },
        
      ],

      title: "资金账号",
      dialogVisible: false,
      dialogType: "new",
      datas: [],
      selections: [],

      listLoading: true,
      total: 0,
      listQuery: {
        name: "",
        page: 1,
        page_size: 15,
      },
    };
  },
  computed: {
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },

  created() {
    this.getAccountList();
  },
  methods: {
    getAccountList() {
      this.listLoading = true;
      getAccounts(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.total = res.count;
          this.listLoading = false;
        })
        .catch((error) => {
          this.$message.error("获取数据失败!" + error);
          this.listLoading = false;
        });
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getAccountList();
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },

    dataFormatter(row, column, cellValue, index) {
      if (column.property == "init_money") {
        return row.init_money && row.init_money.toFixed(2);
      } else if (column.property == "balance") {
        return row.balance && row.balance.toFixed(2);
      } else {
        return cellValue;
      }
    },

    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delAccount(row.id);
          this.getAccountList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "fail",
            message: "删除失败!" + err,
          });
        });
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        if (column.property === "init_money" || column.property === "balance") {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });
      return sums;
    },
    //批量删除
    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          // const res = await delAccounts(sel_ids);
          this.getAccountList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "删除失败!" + err,
          });
        });
    },

    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";

        let res = null;
        if (isEdit) {
          res = await updateAccount(this.form);
        } else {
          res = await addAccount(this.form);
        }

        this.getAccountList();

        const { name, balance } = res;

        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>收付款账号: ${name}</div>
              <div>余额: ${balance}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
</style>